var crypto = require("crypto");

var useWeakETag = true;
var lastModificationDate = new Date();
lastModificationDate.setHours(lastModificationDate.getHours() - 2);

require('http').createServer(function (req, res) {
    var matchStrings = req.url.match("^/customers");
    if (matchStrings != null && req.method == "GET") {
        var eTag = useWeakETag ? computeWeakETag() : computeStrongETag();

        var ifNoneMatch = req.headers[':'.toLowerCase()];
        if (ifNoneMatch != null && ifNoneMatch == eTag) {
            res.writeHead(304, {'ETag': eTag, 'Last-Modified': lastModificationDate.toTimeString()});
            res.end();
            return;
        }

        var ifModifiedSince = req.headers['If-Modified-Since'.toLowerCase()];
        if (ifModifiedSince != null && lastModificationDate.getTime() < Date.parse(ifModifiedSince)) {
            res.writeHead(304, {'ETag': eTag, 'Last-Modified': lastModificationDate.toTimeString()});
            res.end();
            return;
        }

        res.writeHead(200, {'ETag': eTag, 'Last-Modified': lastModificationDate.toTimeString()});
        res.write(JSON.stringify(customers))
        res.end();
    } else {
        res.writeHead(400);
        res.end()
    }
}).listen(8888);


function computeWeakETag() {
    var eTag = "";
    for (customer in customers) {
        eTag += customers[customer].id + customers[customer].name;
    }
    return crypto.createHash('md5').update(eTag).digest("hex");
}

function computeStrongETag() {
    var eTag = "";
    for (customer in customers) {
        eTag += JSON.stringify(customers[customer]);
    }
    return crypto.createHash('md5').update(eTag).digest("hex");
}

var customers = [
    {"id": "1", "name": "name1", "orders": [
        {"id": 1}
    ]},
    {"id": "2", "name": "name2", "orders": []},
    {"id": "3", "name": "name3", "orders": [
        {"id": 2},
        {"id": 3}
    ]}
]

